/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.moedik.controller;

import com.moedik.classes.Bus;
import com.moedik.classes.BusBook;
import com.moedik.classes.City;
import com.moedik.classes.Kalender;
import com.moedik.classes.Pool;
import com.moedik.classes.BusService;
import com.moedik.classes.BusServiceDb;
import com.moedik.classes.User;
import com.moedik.model.ConfigModel;
import com.moedik.model.BusModel;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author SAMMY
 */
public class BusController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        ConfigModel configModel = new ConfigModel();
        String companyName = configModel.getCompanyName();
        request.getSession().setAttribute("companyName", companyName);
        request.setAttribute("title", "Bus");

        BusModel buses = new BusModel();

        if ((request.getParameter("action") == null) || (request.getParameter("action").equals("view"))) {
            if (request.getParameter("city") != null) {
                int cityId = Integer.parseInt(request.getParameter("city"));
                ArrayList<Pool> pools = buses.getPoolServices(cityId);

                request.setAttribute("pools", pools);
                request.setAttribute("city", cityId);
                request.getRequestDispatcher("buses/pool.jsp").forward(request, response);
            } else if (request.getParameter("pool") != null) {
                int poolId = Integer.parseInt(request.getParameter("pool"));

                Kalender cal;

                if (request.getParameter("date") != null) {
                    cal = new Kalender(Long.parseLong(request.getParameter("date")));
                } else {
                    cal = new Kalender();
                }

                ArrayList<BusService> schedules = buses.getServices(poolId, cal);

                request.setAttribute("schedules", schedules);
                request.setAttribute("now", cal);
                request.setAttribute("pool", poolId);
                request.getRequestDispatcher("buses/schedule.jsp").forward(request, response);
            } else {
                ArrayList<City> cities = buses.getCityServices();

                request.setAttribute("cities", cities);
                request.getRequestDispatcher("buses/city.jsp").forward(request, response);
            }
        } else if (request.getParameter("action").equals("confirm_book")) {
            int serviceId = Integer.parseInt(request.getParameter("id"));
            long date = Long.parseLong(request.getParameter("date"));
            BusService service = buses.getService(serviceId);

            Kalender cal = new Kalender(date);

            request.setAttribute("service", service);
            request.setAttribute("date", cal);
            request.getRequestDispatcher("buses/confirm_book.jsp").forward(request, response);
        } else if (request.getParameter("action").equals("book")) {
            User user = (User) request.getSession().getAttribute("user");
            int serviceId = Integer.parseInt(request.getParameter("service_id"));
            long date = Long.parseLong(request.getParameter("date"));
            BusService service = buses.getService(serviceId);

            String bookingCode = buses.book(user.getId(), serviceId, date);

            Kalender cal = new Kalender(date);

            request.setAttribute("user", user);
            request.setAttribute("code", bookingCode);
            request.setAttribute("service", service);
            request.setAttribute("date", cal);
            request.getRequestDispatcher("buses/book.jsp").forward(request, response);
        } else if (request.getParameter("action").equals("manage")) {
            boolean authenticated = (Boolean) request.getSession().getAttribute("authenticated");
            
            if (!authenticated){
                response.sendRedirect("./users?action=login");
            } else {
                if (((User) request.getSession().getAttribute("user")).getRoleId() != 2) {
                    request.getSession().setAttribute("flash", "Silahkan login sebagai manager");
                    response.sendRedirect("./users?action=login");
                }
                else if (request.getParameter("get") != null) {
                    response.setContentType("text/plain");
                    PrintWriter out = response.getWriter();
                    if (request.getParameter("get").equals("pool")) {
                        out.println("<option class=\"defPool\" >Pilih Pool Keberangkatan</option>");
                        int cityId = Integer.parseInt(request.getParameter("city"));
                        ArrayList<Pool> pools = buses.getPoolServices(cityId);
                        Iterator itr = pools.iterator();
                        while (itr.hasNext()) {
                            Pool pol = (Pool) itr.next();
                            out.println("<option value=\"" + pol.getId() + "\">" + pol.getName() + "</option>");
                        }
                    } else if (request.getParameter("get").equals("schedule")) {
                        response.setContentType("text/html;charset=UTF-8");
                        int poolId = Integer.parseInt(request.getParameter("pool"));
                        ArrayList<BusService> schedules = buses.getServices(poolId);
                        request.setAttribute("schedules", schedules);
                        request.getRequestDispatcher("buses/manage_list.jsp").forward(request, response);
                    }
                } else if (request.getParameter("mode") != null) {
                    if (request.getParameter("mode").equals("delete")) {
                        int schedId = Integer.parseInt(request.getParameter("schedule"));
                        buses.deleteService(schedId);
                    } else if (request.getParameter("mode").equals("edit")) {
                        if (request.getMethod().equals("POST")) {
                            int poolFrom = Integer.parseInt(request.getParameter("poolFrom"));
                            int poolTo = Integer.parseInt(request.getParameter("poolTo"));
                            int busId = Integer.parseInt(request.getParameter("bus"));
                            int schedId = Integer.parseInt(request.getParameter("id"));
                            String hour = request.getParameter("hour");
                            int fare = Integer.parseInt(request.getParameter("fare"));
                            String[] days = request.getParameterValues("day[]");
                            String day = "";
                            if (days != null) {
                                if (days.length > 0) {
                                    day += days[0];
                                    int i = 1;
                                    while (i < days.length) {
                                        day += "," + days[i++];
                                    }
                                }
                            }
                            buses.updateService(schedId ,poolFrom, poolTo, busId, hour, fare, day);
                            request.getSession().setAttribute("flash", "Schedule berhasil diedit");
                        }
                        int serviceId = Integer.parseInt(request.getParameter("schedule"));
                        BusServiceDb travel = buses.getServiceDb(serviceId);
                        ArrayList<City> cities = buses.getCityServices();
                        ArrayList<Bus> bus = buses.getBus();
                        ArrayList<Pool> poolsFrom = buses.getPoolsFrom(serviceId);
                        ArrayList<Pool> poolsTo = buses.getPoolsTo(serviceId);
                        request.setAttribute("cities", cities);
                        request.setAttribute("travel", travel);
                        request.setAttribute("buses", bus);
                        request.setAttribute("poolsFrom", poolsFrom);
                        request.setAttribute("poolsTo", poolsTo);
                        request.getRequestDispatcher("buses/manage_edit.jsp").forward(request, response);
                        
                    } else if (request.getParameter("mode").equals("add")) {
                        if (request.getMethod().equals("POST")) {
                            int poolFrom = Integer.parseInt(request.getParameter("poolFrom"));
                            int poolTo = Integer.parseInt(request.getParameter("poolTo"));
                            int busId = Integer.parseInt(request.getParameter("bus"));
                            String hour = request.getParameter("hour");
                            int fare = Integer.parseInt(request.getParameter("fare"));
                            String[] days = request.getParameterValues("day[]");
                            String day = "";
                            if (days != null) {
                                if (days.length > 0) {
                                    day += days[0];
                                    int i = 1;
                                    while (i < days.length) {
                                        day += "," + days[i++];
                                    }
                                }
                            }
                            buses.addService(poolFrom, poolTo, busId, hour, fare, day);
                            request.getSession().setAttribute("flash", "Schedule berhasil ditambahkan");
                        }
                        ArrayList<City> cities = buses.getCityServices();
                        ArrayList<Bus> bus = buses.getBus();
                        request.setAttribute("cities", cities);
                        request.setAttribute("buses", bus);
                        request.getRequestDispatcher("buses/manage_add.jsp").forward(request, response);
                    }
                } else {
                    ArrayList<City> cities = buses.getCityServices();
                    request.setAttribute("cities", cities);
                    request.getRequestDispatcher("buses/manage.jsp").forward(request, response);
                }
            }
        }else if (request.getParameter("action").equals("view_book")) {
            boolean authenticated = (Boolean) request.getSession().getAttribute("authenticated");

            if (!authenticated) {
                response.sendRedirect("./users?action=login");
            } else {
                if (((User) request.getSession().getAttribute("user")).getRoleId() != 3) {
                    request.getSession().setAttribute("flash", "Silahkan login sebagai karyawan");
                    response.sendRedirect("./users?action=login");
                } else if (request.getParameter("mode") != null) {
                    if (request.getParameter("mode").equals("delete_book")) {
                        int id = Integer.parseInt(request.getParameter("id"));
                        buses.deleteBusBook(id);
                        //view booking list
                        ArrayList<BusBook> busBooks = buses.getBusBooks();
                        request.getSession().setAttribute("flash", "Penghapusan berhasil.");
                        request.setAttribute("busBooks", busBooks);
                        request.getRequestDispatcher("buses/book_list.jsp").forward(request, response);
                    }
                } else {
                    //view booking list
                    ArrayList<BusBook> busBooks = buses.getBusBooks();
                    request.setAttribute("busBooks", busBooks);
                    request.getRequestDispatcher("buses/book_list.jsp").forward(request, response);
                }
            }
        } else if (request.getParameter("action").equals("report")) {
            if (((User) request.getSession().getAttribute("user")) == null) {
                response.sendRedirect("./users?action=login");
            }else if (((User) request.getSession().getAttribute("user")).getRoleId() != 2) {
                request.getSession().setAttribute("flash", "Silahkan login sebagai manager");
                response.sendRedirect("./users?action=login");
            } else if(request.getMethod().equals("POST")){
                int year = Integer.parseInt(request.getParameter("year"));
                ArrayList<Integer> count = buses.getReport(year);
                Calendar cal = Calendar.getInstance();
                cal.set(Calendar.YEAR, year);
                request.setAttribute("count", count);
                request.setAttribute("year", year);
                request.getRequestDispatcher("buses/report.jsp").forward(request, response);
            }else {
                ArrayList<Integer> count = buses.getReport();
                ArrayList<City> cities = buses.getCityServices();
                Calendar cal = Calendar.getInstance();
                request.setAttribute("count", count);
                request.setAttribute("year", cal.get(Calendar.YEAR));
                request.getRequestDispatcher("buses/report.jsp").forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
